package com.nosnow.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nosnow.edu.entity.EduSubject;
import com.nosnow.edu.entity.excel.SubjectData;
import com.nosnow.edu.service.EduSubjectService;
import com.nosnow.handler.SnowflakeException;

/**
 * @author by bingHeng
 * @version 1.0
 * @Create 2020/4/4 17:52
 *
 * 读取excel监听器
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    /**
     *
     * 因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象，因而不能实现数据库操作
     *
     * 解决方式：使用构造器将对象传过来
     */
    public EduSubjectService subjectService;

    public SubjectExcelListener() {}

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /**
     * 判断一级分类或者二级分类是否在库中已经存在
     * @param eduSubjectService
     * @param name
     * @return
     */
    private EduSubject existSubject(EduSubjectService eduSubjectService, String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        if(pid == null) {
            wrapper.eq("parent_id", "0");
        } else {
            wrapper.eq("parent_id", pid);
        }
        EduSubject subject = eduSubjectService.getOne(wrapper);
        return subject;
    }

    // 读取方法: 一行一行的读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {

        // 1. 判断文件中是否存在真实数据
        if(subjectData == null) {
            throw new SnowflakeException(2001, "文件数据为空");
        }

        // 2. 一行一行读取，每次读取两个值，第一个值为一级分类，第二个值为二级分类
        // 2.1 判断一级分类是否重复
        EduSubject oneSubject = this.existSubject(subjectService, subjectData.getOneSubjectName(), null);
        if(oneSubject == null) {
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(oneSubject);
        }

        // 2.2 判断二级分类是否重复
        EduSubject twoSubject = this.existSubject(subjectService, subjectData.getTwoSubjectName(), oneSubject.getId());
        if(twoSubject == null) {
            twoSubject = new EduSubject();
            twoSubject.setParentId(oneSubject.getId());
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(twoSubject);
        }
    }

    // 读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
